<script lang="ts" setup>
import { copyFileURL, readDirURL } from '@/api';
import type { File, TableHeader, TableItem } from '@/types/fs';

const leftTableHeaders: TableHeader[] = [
  { title: "文档名称", key: "filename" },
  { title: "文件大小", key: "size" },
  { title: "所属域", key: "domain" },
];

const rightTableHeaders: TableHeader[] = [
  { title: "文档名称", key: "filename" },
  { title: "所属域", key: "domain" },
];

const useTable = async (dirOnly: boolean = false) => {
  const path = ref([""] as string[]);
  const breadcrumbsItems = computed(() => {
    const items = path.value.map((v, i) => ({
      title: v ? v : "/",
      disabled: false,
      index: i,
      // to: `/fs/file${path.value.slice(0, i + 1).join('/')}`
    }));
    return items;
  });

  const useTableData = async () => {
    const url = computed(() => `${readDirURL}${path.value.join("/")}`);
    const { data, refresh } = await useFetch<File[]>(url);
    if (dirOnly && data?.value) {
      data.value = data?.value?.filter((v) => v.isDir);
    }
    return {
      data: ref(
        data?.value
          ?.map((v) => ({
            filename: v.filename,
            isDir: v.isDir,
            domain: v.domain,
            size: v.size,
          }))
          .sort((x, y) => {
            if (x.isDir && !y.isDir) {
              return -1;
            }
            if (!x.isDir && y.isDir) {
              return 1;
            }
            return x.filename.localeCompare(y.filename);
          })
      ),
      refresh,
    };
  };
  const { data: tableItems, refresh } = await useTableData();

  const enterDir = async (dir: string) => {
    path.value.push(dir);
    const { data } = await useTableData();
    tableItems.value = data.value;
  };

  const goback = async (i: number = -1) => {
    if (i === -1) {
      path.value.pop();
      const { data } = await useTableData();
      tableItems.value = data.value;
    } else {
      path.value = path.value.slice(0, i + 1);
      const { data } = await useTableData();
      tableItems.value = data.value;
    }
  };

  return {
    path,
    breadcrumbsItems,
    tableItems,
    enterDir,
    goback,
    refresh
  };
};

const {
  path: leftPath,
  breadcrumbsItems: leftBreadcrumbsItems,
  tableItems: leftTableItems,
  enterDir: leftEnterDir,
  goback: leftGoback,
} = await useTable();
const leftSelectedItems = ref([] as TableItem[]);

const {
  path: rightPath,
  breadcrumbsItems: rightBreadcrumbsItems,
  tableItems: rightTableItems,
  enterDir: rightEnterDir,
  goback: rightGoback,
} = await useTable(true);
const rightSelectedItems = ref([] as TableItem[]);

const moveFiles = async () => {
  if (leftSelectedItems.value.length === 0) {
    return;
  }
  const filename = leftSelectedItems.value[0].filename;
  const size = leftSelectedItems.value[0].size;
  const src = leftPath.value.concat(filename).join("/");
  const dst = computed(() => {
    if (rightSelectedItems.value.length === 0) {
      return rightPath.value.join("/");
    }
    const filename = rightSelectedItems.value[0].filename;
    return rightPath.value.concat(filename).join("/");
  });
  console.log("src:", src);
  console.log("dst:", dst);

  $fetch(`${copyFileURL}`, {
    method: "POST",
    body: JSON.stringify({ src, dst: dst.value.concat('/') }),
  })
  await $fetch("http://49.232.250.113:8080/transfer", {
    method: "POST",
    body: JSON.stringify({ filename, src: src, dst: dst.value, size }),
  }).then((res) => {
    console.log("then", res);
    navigateTo("/fs/transfer");
  });
};
</script>

<template>
  <div>
    <v-row>
      <v-col>
        <div class="text-h6">选择被移动的文件：</div>
        <v-row class="align-center" justify="start" no-gutters>
          <div v-if="leftPath.length > 1">
            <v-icon icon="mdi-arrow-up" @click="leftGoback()" />
          </div>

          <div v-else>
            <v-icon color="grey" icon="mdi-arrow-up" />
          </div>

          <span class="ml-4"> 当前文件夹路径： </span>
          <v-breadcrumbs :items="leftBreadcrumbsItems">
            <template #divider>
              <v-icon icon="mdi-chevron-right" />
            </template>
          </v-breadcrumbs>
        </v-row>
        <v-data-table
          v-model="leftSelectedItems"
          :headers="leftTableHeaders"
          :items="leftTableItems"
          item-value="filename"
          hide-default-footer
          select-strategy="single"
          show-select
          return-object
        >
          <template #item.filename="{ item }">
            <div
              v-if="item.isDir"
              class="flex items-center"
              @click="leftEnterDir(item.filename)"
            >
              <div class="mr-2">
                <v-icon color="blue" icon="mdi-folder" />
              </div>
              <span>
                {{ item.filename }}
              </span>
            </div>

            <div v-else class="flex items-center">
              <div class="mr-2">
                <v-icon icon="mdi-file" />
              </div>
              <span>
                {{ item.filename }}
              </span>
            </div>
          </template>

          <template #item.size="{ item }">
            <div v-if="item.isDir">-</div>
            <div v-else>
              {{ transformSize2HumanReadable(item.size) }}
            </div>
          </template>

          <template #item.domain="{ item }">
            <v-chip v-if="item.domain.startsWith('云')" :text="item.domain" color="blue" />
            <v-chip v-else-if="item.domain.startsWith('边')" :text="item.domain" color="green" />
            <v-chip v-else-if="item.domain.startsWith('端')" :text="item.domain" color="orange" />
          </template>
        </v-data-table>
      </v-col>

      <v-divider opacity="2" vertical />

      <v-col>
        <div class="text-h6">选择目的文件夹：</div>
        <v-row class="align-center" justify="start" no-gutters>
          <div v-if="rightPath.length > 1">
            <v-icon icon="mdi-arrow-up" @click="rightGoback()" />
          </div>

          <div v-else>
            <v-icon color="grey" icon="mdi-arrow-up" />
          </div>

          <span class="ml-4"> 当前文件夹路径： </span>
          <v-breadcrumbs :items="rightBreadcrumbsItems">
            <template #divider>
              <v-icon icon="mdi-chevron-right" />
            </template>

            <template #title="{ item }">
              <NuxtLink :to="item.href">{{ item.title }}</NuxtLink>
            </template>
          </v-breadcrumbs>
        </v-row>
        <v-data-table
          v-model="rightSelectedItems"
          :headers="rightTableHeaders"
          :items="rightTableItems"
          item-value="filename"
          hide-default-footer
          select-strategy="single"
          show-select
          return-object
        >
          <template #item.filename="{ item }">
            <div
              class="flex items-center"
              @click="rightEnterDir(item.filename)"
            >
              <div class="mr-2">
                <v-icon color="blue" icon="mdi-folder" />
              </div>
              <span>
                {{ item.filename }}
              </span>
            </div>
          </template>

          <template #item.domain="{ item }">
            <v-chip v-if="item.domain.startsWith('云')" :text="item.domain" color="blue" />
            <v-chip v-else-if="item.domain.startsWith('边')" :text="item.domain" color="green" />
            <v-chip v-else-if="item.domain.startsWith('端')" :text="item.domain" color="orange" />
          </template>
        </v-data-table>
      </v-col>
    </v-row>
    <div class="flex justify-end">
      <v-btn color="primary" @click="moveFiles"> 移动文件 </v-btn>
    </div>
  </div>
</template>
